package com.hpin.fansea.sale;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.adapter.GoodsListAdapter;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.GroupResBean;
import com.hpin.fansea.home.WaitCircleActivity;
import com.hpin.fansea.pulltorefush.PullToRefreshBase;
import com.hpin.fansea.pulltorefush.PullToRefreshListView;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 商品列表
 * Created by Aaron on 15/10/22.
 */
public class GoodsActivity extends BaseActivity {

    private int currentIndex;
    private String categoryId;
    private PullToRefreshListView plv_goods;
    private List<GroupResBean.GroupResult> groupResults = new ArrayList<>();
    private GoodsListAdapter mAdapter;
    private TextView tv_title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_goods_list);

        categoryId = getIntent().getStringExtra("categoryId");

        initWidget();

        tv_title.setText(getIntent().getStringExtra("categoryName"));

        getGoods();

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);

        iv_left.setOnClickListener(this);
        tv_title = (TextView) findViewById(R.id.tv_title);

        plv_goods = (PullToRefreshListView) findViewById(R.id.plv_goods);

        mAdapter = new GoodsListAdapter(this, groupResults);

        plv_goods.setAdapter(mAdapter);

//        ListView refreshableView = plv_goods.getRefreshableView();

        plv_goods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                --position;

//                LogUtil.e("tag", "点击事件=====" + position);

                Intent mIntent = new Intent(GoodsActivity.this, GoodsDetailActivity.class);
                mIntent.putExtra("groupBuyId", groupResults.get(position).id_);
                startActivity(mIntent);

            }
        });

        plv_goods.setMode(PullToRefreshBase.Mode.BOTH);

        plv_goods.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(GoodsActivity.this, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                currentIndex = 0;
                groupResults.clear();
                getGoods();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(GoodsActivity.this, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                getGoods();
            }
        });

    }

    private void getGoods() {

        HttpUtil.getInstance().setGetRequest("获取中...", this, Constant.WEB_ROOT + Constant.GOODSLIST + "?token=" + sp.getString(Constant.token, "") +
                        "&systemType=" + Constant.SYSTEM_TYPE + "&communityId=" + sp.getString(Constant.communityId, "") +
                        "&categoryId=" + categoryId + "&orderBy=&orderSeq=" + "&pageSize=" + Constant.PAGECOUNT + "&pageIndex=" + (++currentIndex)

                , new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        plv_goods.onRefreshComplete();

                        try {

                            GroupResBean groupResBean = JSONObject.parseObject(str, GroupResBean.class);

                            if (Constant.STATUS_SUCESS.equals(groupResBean.status)) {

                                List<GroupResBean.GroupResult> groupResults = groupResBean.result;

                                if (currentIndex == 1 && groupResults.size() == 0) {

                                    //一条数据都没用的时候跳转到敬请期待页面
                                    Intent mIntent = new Intent(GoodsActivity.this, WaitCircleActivity.class);
                                    startActivity(mIntent);
                                    finish();
                                    return;
                                }

                                if (groupResults.size() == 0) {
                                    showToast("没有更多数据了");
                                    return;
                                }

                                setListView(groupResults);

                                mAdapter.notifyDataSetChanged();

                            } else {
                                showToast(groupResBean.message);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, new HttpUtil.FailListener() {
                    @Override
                    public void setOnFailListener() {
                        plv_goods.onRefreshComplete();
                    }
                }
        );

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:

                finish();

                break;

        }

    }

    /**
     * 判断是否有重复并更新
     */
    private void setListView(List<GroupResBean.GroupResult> tempGuideLists) {

        if (tempGuideLists == null || tempGuideLists.size() == 0)
            return;

        if (groupResults.size() == 0) {

            groupResults.addAll(tempGuideLists);
            return;
        }

        for (GroupResBean.GroupResult goods : tempGuideLists) {
            boolean exist = false;
            for (GroupResBean.GroupResult g : groupResults) {
                if (goods.id_.equals(g.id_)) {
                    exist = true;
                    break;
                }
            }
            if (!exist)
                groupResults.add(goods);
        }

    }

}
